<template>
  <div class="tw-header"
    v-fix="isFixed && fixedDistance"
    :style="{backgroundColor: bgColor || '', color: color || ''}">
    <div ref="header-inner"
      class="tw-header-inner">
      <a ref="header-left"
        class="tw-header-left"
        :href="titleHref">
        <img v-if="logo && logo.length>0"
          class="tw-header-logo"
          :src="`${$twApp.fileBaseUrl}${logo[0].localPath}`"
          alt="logo" />
        <h1 class="tw-header-title">{{title}}</h1>
      </a>

      <ul class="tw-header-nav"
        ref="headernavs">
        <li :class="{xactive:nav.active, [`js-xheadernav${idx}`]:true, xparent: nav.children}"
          :style="{color: nav.active && activeColor ? activeColor: ''}"
          v-for="(nav,idx) in containableNavs"
          :key="containableNavs.length + '_' + idx">
          <a v-if="nav.href"
            :href="nav.href + (dataIsFromPortal && nav.pageType !== 4 ? `?pageId=${nav.pageId}` : '')"
            :target="nav.target"
            :style="{borderBottomColor: nav.active && activeColor ? activeColor: ''}"
            @click="handleNavClick(nav, navs, $event)">
            <span>{{nav.name}}</span>
          </a>

          <a v-else
            :style="{borderBottomColor: nav.active && activeColor ? activeColor: ''}"
            @click="handleNavClick(nav, navs, $event)">
            <span>{{nav.name}}</span>
          </a>

          <tw-poppane v-if="nav.children"
            :key="containableNavs.length"
            :class="['xheadernav', `js-poppane-${idx}`, `x${_uid}`]"
            :switch="`.js-xheadernav${idx}`">
            <ul class="tw-header-menus ">
              <li v-for="(lv1Menu, lv1Idx) in nav.children"
                :key="`${idx}-${lv1Idx}`"
                :class="[lv1Menu.active?'xactive':'', `js-xheadernav${idx}-${lv1Idx}`, lv1Menu.children?'xparent':'']">
                <template v-if="showMenu(lv1Menu)">
                  <a v-if="lv1Menu.href"
                    :href="lv1Menu.href + (dataIsFromPortal && lv1Menu.pageType !== 4 ? `?pageId=${lv1Menu.pageId}&parentId=${nav.pageId}` : '')"
                    :target="lv1Menu.target"
                    @click="handleNavClick(lv1Menu, navs, $event)">{{lv1Menu.name}}</a>
                  <a v-else>
                    <span>{{lv1Menu.name}}</span>
                  </a>

                  <tw-poppane v-if="lv1Menu.children"
                    :class="['xheadernav', `js-poppane-${idx}-${lv1Idx}`, `x${_uid}`]"
                    :switch="`.js-xheadernav${idx}-${lv1Idx}`"
                    placement="right-top">
                    <ul class="tw-header-menus ">
                      <li v-for="(lv2Menu, lv2Idx) in lv1Menu.children"
                        :key="`${idx}-${lv1Idx}-${lv2Idx}`"
                        :class="[lv2Menu.active?'xactive':'', `js-xheadernav${idx}-${lv1Idx}-${lv2Idx}`]">
                        <template v-if="showMenu(lv2Menu)">
                          <a v-if="lv2Menu.href"
                            :href="lv2Menu.href + (dataIsFromPortal && lv2Menu.pageType !== 4 ? `?pageId=${lv2Menu.pageId}&parentId=${lv1Menu.pageId}&rootPageId=${nav.pageId}` : '')"
                            :target="lv2Menu.target"
                            @click="handleNavClick(lv2Menu, navs, $event)">{{lv2Menu.name}}</a>
                          <a v-else>
                            <span>{{lv2Menu.name}}</span>
                          </a>
                        </template>
                      </li>
                    </ul>
                  </tw-poppane>
                </template>
              </li>
            </ul>
          </tw-poppane>
        </li>
      </ul>

      <div ref="header-right"
        class="tw-header-right">
        <!-- 搜索框 -->
        <div v-if="useSearch"
          class="tw-libnavs-search"
          :style="{borderColor: borderColorSearch,position: 'relative',width:widthSearch,borderRadius:borderRadiusSearch,marginLeft:marginLeftSearch}">
          <input type="text"
            v-model="value"
            :style="{paddingRight: inputPaddingLeftSearch, fontSize: fontSizeSearch, color: colorSearch}"
            @input="$emit('input', $event.target.value)"
            @keyup.enter="handleSearch"
            :placeholder="placeholderSearch" />
          <div class="tw-libnavs-search-btn"
            @click="handleSearch">
            <i class="icon iconfont"
              :style="{fontSize: iconFontSizeSearch, color: iconColorSearch}">&#xe605;</i>
          </div>
        </div>
        <!-- /搜索框 -->

        <template v-if="$twApp.user && $twApp.user.userId">
          <template v-if="userInfoList && userInfoList.length>0">
            <a class="tw-header-user js-userinfo">
              <span class="tw-header-notice">
                <img v-if="headImgs"
                  class="tw-header-user-avatar"
                  :src="headImgs">
                <img v-else
                  class="tw-header-user-avatar"
                  src="@assets/avatar.png" />
                <i v-if="newNotices.count>0">{{newNotices.count}}</i>
              </span>
              <span class="tw-header-username">{{$twApp.user.realName
                || '个人中心'}}</span>
            </a>

            <tw-poppane class="xheadernav"
              :class="[`x${_uid}`]"
              switch=".js-userinfo">
              <ul class="tw-header-menus">
                <li>
                  <a class="tw-header-notice"
                    v-if="noticeHref"
                    :href="noticeHref"
                    target="_blank">
                    <span>消息中心</span>
                    <span v-if="newNotices.count>0">({{newNotices.count}})</span>
                  </a>
                </li>
                <li v-for="(userInfo, idx) in userInfoList"
                  :key="idx">
                  <a v-if="userInfo.href"
                    :href="userInfo.href"
                    :target="userInfo.target">{{userInfo.name}}</a>
                  <a v-if="userInfo.isLogoff && logoffhref"
                    @click="$twApp.logoff();logoffHome();">退出</a>
                  <a v-else-if="userInfo.isLogoff"
                    @click="$twApp.logoff()">退出</a>
                </li>
              </ul>
            </tw-poppane>
          </template>
          <template v-else>
            <a v-if="noticeHref"
              class="tw-header-notice"
              target="_blank"
              :href="noticeHref"
              title="消息中心">
              <span class="iconfont">&#xe6f6;</span>
              <i v-if="newNotices.count>0">{{newNotices.count}}</i>
            </a>

            <a class="tw-header-user">
              <img class="tw-header-user-avatar"
                src="@assets/avatar.png" />
              <span class="tw-header-username">{{$twApp.user.realName
                || '个人中心'}}</span>
            </a>

            <a v-if="!noLogoff"
              class="tw-header-logoff"
              @click="$twApp.logoff()">
              <span class="iconfont">&#xe686;</span>
            </a>
          </template>
        </template>

        <template v-else>
          <a v-if="!notLoginBtn"
            class="tw-header-loginbtn"
            :href="$twApp.eco.loginPage">登录</a>
          <a class="tw-header-otherlink"
            target="_blank"
            :style="{color: otherLinkColor}"
            :href="toOhterUrl"
            v-if="ifOutLink && !otherLinkMulit">{{otherLink}}</a>
          <a class="tw-header-otherlink"
            target="_blank"
            v-for="(url, idx) in toOhterUrls"
            :href="url.url"
            :key="idx">{{url.name}}</a>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import props from './props'
import page from '../tw-lib-base/page/mixins'

export default {
  name: 'header-navigate',

  props,

  mixins: [page],

  data() {
    return {
      resizing: false,
      containableNavs: []
    }
  },

  computed: {
    toOhterUrls() {
      if (this.ifOutLink && this.otherLinkMulit) {
        const urls = []
        const otherLinks = this.otherLink.split(',')
        this.toOhterUrl.split(',').forEach((itm, idx) => {
          urls.push({
            name: otherLinks[idx],
            url: itm
          })
        })
        return urls
      } else {
        return []
      }
    },

    navs() {
      const roleIdList = this.$twApp.user.roleIdList || []
      const result = JSON.parse(
        JSON.stringify(this.dataIsFromPortal ? this.apiNavList : this.navList)
      )
      const pathname = window.location.pathname
      const navList = []
      const navMore = []

      result.forEach((item, idx) => {
        // 判断用户所在的机构类型是否有该导航的权限
        if (
          !item.pageOrgTypes ||
          item.pageOrgTypes.length === 0 ||
          item.pageOrgTypes.includes(vm.$twApp.user.orgType)
        ) {
          // 判断用户所在的角色是否有该导航的权限
          if (
            !item.roles ||
            item.roles.length === 0 ||
            roleIdList.filter(role => item.roles.includes(role)).length > 0
          ) {
            if (item.activeText) {
              item.active = pathname.includes(item.activeText)
            } else if (item.href) {
              if (
                pathname.includes(
                  item.href.replace(/^\./, '').replace('.html', '')
                )
              ) {
                item.active = true
              }
            }

            if (
              typeof this.navVifFunction === 'function' &&
              !this.navVifFunction(item, result)
            ) {
              return
            }

            if (this.isShrink && this.curIndex > 0 && idx >= this.curIndex) {
              navMore.push(item)
            } else {
              navList.push(item)
            }

            // navList.push(item)
          }
        }
      })

      if (this.isShrink && navMore.length > 0) {
        navList.push({
          name: '更多',
          activeText: 'navmore',
          children: navMore
        })
      }

      return navList
    },

    style() {
      return {
        paddingY: this.paddingY,
        paddingX: this.paddingX,
        logoHeight: this.logoHeight,
        color: this.color,
        bgColor: this.bgColor,
        activeColor: this.activeColor,
        iconColor: this.iconColor,
        navFontSize: this.navFontSize,
        titleFontSize: this.titleFontSize,
        titleIsBold: this.titleIsBold,
        enableMediaQuery: this.enableMediaQuery,
        mediaPointLength: this.mediaPoint.length,
        mediaPointWidthLength: this.mediaPointWidth.length,
        iconColorHover: this.iconColorHover,
        poppaneBg: this.poppaneBg,
        poppaneColor: this.poppaneColor,
        menuActiveBg: this.menuActiveBg,
        menuActiveColor: this.menuActiveColor,
        poppaneShadownColor: this.poppaneShadownColor,
        loginBtnColor: this.loginBtnColor,
        loginBtnHoverColor: this.loginBtnHoverColor,
        loginBtnBg: this.loginBtnBg,
        loginBtnHoverBg: this.loginBtnHoverBg,
        loginBorderRadius: this.loginBorderRadius,
        mrLength: this.mrLength,
        fixedShadowColor: this.fixedShadowColor,
        ifOutLink: this.ifOutLink
      }
    }
  },

  methods: {
    handleNavClick(nav, navs, event) {
      if (typeof this.clickNavHandler === 'function') {
        const result = this.clickNavHandler(nav, navs)

        if (result === false) {
          event.preventDefault()
        }
      }
    },

    showMenu(menu) {
      const roleIdList = this.$twApp.user.roleIdList || []

      if (
        !menu.roles ||
        menu.roles.length === 0 ||
        roleIdList.filter(role => menu.roles.includes(role)).length > 0
      ) {
        return true
      } else {
        return false
      }
    },

    setStyle() {
      let style = `
        ::root {
          color: ${this.color};
          background: ${this.bgColor};
        }

        ::root .tw-header-logo {
          height: ${this.logoHeight};
          margin-right: ${this.mrLength}
        }

        ::root .tw-header-title {
          font-size: ${this.titleFontSize};
          font-weight: ${this.titleIsBold ? '700' : '400'};
          line-height: ${this.titleLineHeight};
          vertical-align: middle;
        }

        ::root .tw-header-nav > li:hover > a,
        ::root .tw-header-nav > li:hover > .tw-triangle.xdown {
          color: ${this.activeColor};
        }

        ::root .tw-header-nav > li > a {
          font-size: ${this.navFontSize};
        }

        ::root .tw-header-nav > li.xactive > a,
        ::root .tw-header-nav > li > a.xactive {
          color: ${this.activeColor};
          border-bottom-color: ${this.activeColor};
        }

        ::root .tw-header-right .iconfont {
          color: ${this.iconColor};
        }

        ::root .tw-header-right .iconfont:hover {
          color: ${this.iconColorHover};
        }

        ::root.tw-poppane.xheadernav {
          background-color: ${this.poppaneBg};
          box-shadow: 0 3px 6px ${this.poppaneShadownColor};
        }

        ::root .tw-header-menus > li > a {
          color: ${this.poppaneColor};
        }

        ::root .tw-header-menus > li > a:hover {
          color: ${this.menuActiveColor};
          background-color: ${this.menuActiveBg};
        }

        ::root .tw-header-loginbtn {
          font-size: ${this.loginBtnFontSize};
          color: ${this.loginBtnColor};
          background: ${this.loginBtnBg};
          border-radius: ${this.loginBorderRadius};
        }

        ::root .tw-header-loginbtn:hover {
          color: ${this.loginBtnHoverColor};
          background: ${this.loginBtnHoverBg};
        }

        ::root.xfixed {
          box-shadow: ${
            this.fixedShadowColor
              ? `0 2px 9px ${this.fixedShadowColor}`
              : 'none'
          };
        }
      `

      if (this.paddingY) {
        style += `
          ::root {
            padding-top: ${this.paddingY};
            padding-bottom: ${this.paddingY};
          }
        `
      }

      if (this.paddingX) {
        style += `
          ::root {
            padding-left: ${this.paddingX};
            padding-right: ${this.paddingX};
          }
        `
      }

      if (
        this.enableMediaQuery &&
        this.mediaPoint &&
        this.mediaPoint.length > 0
      ) {
        for (let i = 0; i < this.mediaPoint.length; i++) {
          style += `
            @media (min-width: ${this.mediaPoint[i]}) {
              ::root > .tw-header-inner {
                width: ${this.mediaPointWidth[i]};
              }
            }
          `
        }
      }

      if (this.useSearch) {
        style += `
          // ::root .tw-libnavs-body {
          //   align-items: center;
          // }

          ::root .tw-libnavs-search {
            margin-left: 20px;
          }

          ::root .tw-libnavs-search input {
            padding: ${this.inputPaddingSearch};
          }

          ::root .tw-libnavs-search-btn:hover .iconfont {
            color: ${this.iconHoverColorSearch} !important;
          }

          ::root .tw-libnavs-search input::-webkit-input-placeholder {
            color: ${this.placeholderColorSearch};
          }
        `
        if (this.iconBgColorSearch) {
          style += `
            ::root .tw-libnavs-search-btn {
              background-color: ${this.iconBgColorSearch};
            }

            ::root .tw-libnavs-search-btn:hover .icon{
              color: ${this.iconHoverColorSearch} !important;
            }
          `
        }
      }

      if (this.isShrink) {
        style += `
          ::root .tw-header-title {
            white-space: nowrap;
          }
          ::root .tw-header-nav > li {
            white-space: nowrap;
          }
        `
      }

      if (this.isFixed) {
        style += `
          ::root.tw-header.xfixed {
            position: fixed!important;
          }

          .tw-poplayer {
            z-index: ${this.navShrinkzIndex};
          }
        `
      }

      if (this.ifOutLink && this.otherLinkMulit) {
        style += `
          ::root .tw-header-right .tw-header-otherlink {
            color: ${this.otherLinkColor};
            line-height: 1;
            position: relative;
            bottom: auto;
            right: auto;
          }
          ::root .tw-header-right .tw-header-otherlink + .tw-header-otherlink {
            margin-left: 10px;
            padding: 0 10px;
            border-left: 1px solid ${this.otherLinkColor};
          }
        `
      }

      this.addStyle(style)
    },

    addStyle(style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl =
        document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style
        .replace(/::root/gm, `.x${this._uid}`)
        .replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    handleSearch() {
      this.$emit('search', this.value)
      if (typeof this.clickFn === 'function') {
        this.clickFn(this.value, this)
      } else {
        if (this.linkSearch) {
          let hreflink = '?'
          if (this.linkSearch.includes('?')) {
            hreflink = '&'
          }

          window.location.href =
            this.linkSearch + hreflink + 'search=' + this.value
        }
      }
    },

    // 获取用户头像
    getUserInfo() {
      var vm = this

      window.axios
        .post(this.$twApp.gateway + '/openapi-uc/uc/getUserBaseInfo', null)
        .then(function(response) {
          if (response.data.responseEntity.user.facePicture) {
            vm.headImgs =
              vm.$twApp.gateway +
              '/fs/media' +
              response.data.responseEntity.user.facePicture
          } else {
            vm.headImgs = ''
          }
        })
        .catch(function(error) {
          vm.$message({
            message: error.data.serverResult.resultMessage,
            type: 'error'
          })
          console.log(error)
        })
    },

    // 重新放置导航
    layNavs() {
      this.containableNavs = this.navs

      this.$nextTick(() => {
        const innerWidth = this.$refs['header-inner'].offsetWidth
        const leftWidth = this.$refs['header-left'].offsetWidth
        const rightWidth = this.$refs['header-right'].offsetWidth
        const navWidth = innerWidth - leftWidth - rightWidth
        const newNavs = []
        const moreNavs = []

        const lv1NavElements = this.$refs['header-inner'].querySelectorAll(
          '.tw-header-nav > li'
        )

        for (let i = 0; i < lv1NavElements.length; i++) {
          if (
            lv1NavElements[i].offsetLeft + lv1NavElements[i].offsetWidth <
            navWidth
          ) {
            newNavs.push(this.navs[i])
          } else {
            moreNavs.push(this.navs[i])
          }
        }

        if (moreNavs.length > 0) {
          newNavs.push({
            name: '更多',
            activeText: 'navmore',
            children: moreNavs
          })
        }

        this.containableNavs = newNavs
      })
    },

    // 页面大小切换
    resizeWindow() {
      if (!this.resizing) {
        this.layNavs()
        this.resizing = true

        setTimeout(() => {
          this.resizing = false
          this.layNavs()
        }, 300)
      }
    },

    // 跳到登录模块
    logoffHome() {
      window.location.href = './index.html#login'
      location.reload(true)
    }
  },

  mounted() {
    this.setStyle()
    window.addEventListener('resize', this.resizeWindow)
  },

  created() {
    var vm = this
    if (this.$twApp.user.userId) {
      this.getUserInfo()
    }
  },

  watch: {
    navs: {
      immediate: true,
      handler(val) {
        this.layNavs()
      }
    },

    style: {
      deep: true,
      handler() {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
